import ArrayList from "../ArrayList";
import { IStack } from "./types";

export default class Stack<T = number> implements IStack<T> {
    private al: ArrayList<T>
    constructor() {
        this.al = new ArrayList();
    }

    /**
     * 获取栈中元素的数量k
     */
    size() {
        return this.al.size();
    }

    /**
     * 判断栈是否为空
     */
    isEmpty() {
        return this.size() === 0;
    }

    /**
     * 入栈
     * @param element 
     */
    push(element: T) {
        this.al.add(element);
    }

    /**
     * 出栈
     */
    pop() {
        const i = this.size() - 1;
        (i) < 0 ? 0 : i
        return this.al.remove((i) < 0 ? 0 : i)
    }

    /**
     * 获取栈顶元素
     */
    top() {
        const i = this.size() - 1;
        (i) < 0 ? 0 : i
        return this.al.get((i) < 0 ? 0 : i)
    }

    /**
     * 遍历栈
     * @param cb 
     */
    forEach(cb: (ele: T, i: number) => boolean) {
        const arr = this.al.array;
        let len = this.size(),
            i = len - 1;
        for (; i >= 0; i--) {
            cb(arr[i]!, i)
        }
    }

    /**
     * 清空栈
     */
    clear() {
        this.al.clear();
    }
} 